//
//  KSImageSelectUtil.swift
//  PigManager
//
//  Created by Ken on 2019/1/21.
//  Copyright © 2019 Much. All rights reserved.
//  图片选择展示工具

import UIKit
import SKPhotoBrowser

import Kingfisher
import Photos
import AVFoundation
import AVKit
var filemaxImageLenght:CGFloat = 1000
var filemaxSizeKB:CGFloat = 380

protocol KSImageUtilDelegate: AnyObject {
    // 开始要弹出选择框, 用于提前调用定位
    func beginShowPicker()
    func dealBeforeAddImages(_ util:KSImageSelectUtil, imgs:[UIImage]) -> [UIImage]  // 添加到图片列表前处理图片，比如加水印等
    func addImages(_ util:KSImageSelectUtil, imgs:[UIImage])  // 把添加了的图片告诉使用者  旧，待替换
    func addImages(_ util:KSImageSelectUtil, imgvideos:[VideoImg])  // 把添加了的图片和视频告诉使用者 新
    
    func addFiles(_ util:KSImageSelectUtil, files:[VideoImg])  // 把添加了的文件告诉使用者
    func deleteImage(_ util:KSImageSelectUtil, index:Int)  //  删除告诉使用者
}
extension KSImageUtilDelegate {
    func beginShowPicker() {
        
    }
    
    func dealBeforeAddImages(_ util:KSImageSelectUtil, imgs:[UIImage]) -> [UIImage]  {  // 扩展为了默认，非必须继承
        return imgs
    }
    func addFiles(_ util:KSImageSelectUtil, files:[VideoImg])  {  // 扩展为了默认，非必须继承
        
    }
    func addImages(_ util:KSImageSelectUtil, imgvideos:[VideoImg]) {
        
    }  // 扩展为了默认，非必须继承
    func addImages(_ util:KSImageSelectUtil, imgs:[UIImage]) {
        
    }  // 扩展为了默认，非必须继承
}
enum ImgViewType { // 只允许删除   只允许添加    只能看   可以任意编辑（删除和添加）
    case deletable,addable,viewOnly,editable
}
public enum SourType {
    case image,video,file
}
public enum ImageSourType {
    case camera,photoLibrary
}
public struct VideoImg {
    var type:SourType?
    var idkey:String? = nil   // id
    var num:String? = nil       // 序号
    var url:String? = nil // 网络url
    var name:String? = nil
    var image:UIImage? = nil
    var data:Data? = nil
    var asset:PHAsset? = nil  // 类型为image 视频 才有 asset  相册的视频  asset格式
    var mediaURL:URL? = nil  // 直接录的视频   是url 路径
    var imageTp:ImageSourType? // 图片来源  拍照或相册
    // 切片总数(上传视频使用)
    var clipCount: Int?
    var clipIndex: Int?
    var clipName: String?
    var isComplete: Bool?
    // 服务器存放切片文件夹名称
    var clipFolder: String?
}

class KSImageSelectUtil: FormItem,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    var collectionView:UICollectionView?
    
    weak var ksDelegate: KSImageUtilDelegate?
    
    
    lazy var dataArray =  [VideoImg]()
    fileprivate let layout = UICollectionViewFlowLayout()
    var viewType:ImgViewType = .editable {
        didSet {
            self.collectionView?.reloadData()
        }
    }
    var maxImgCount = 8 {
        didSet {
            self.collectionView?.reloadData()
        }
    }
    var numberOfRow:CGFloat = 4 {
        didSet {
            layout.itemSize = CGSize(width: self.ks_width/numberOfRow - numberOfRow, height: self.ks_width/numberOfRow - numberOfRow)
            self.collectionView?.reloadData()
        }
    }
    var picType:[PictureType] = [.takePicture,.albumPicture]
    var scrollDirection:UICollectionView.ScrollDirection = .vertical
    // 外面传进来的图片文件资源域名头
    var httpHeader = ""
    func reloadData() {
        self.collectionView?.reloadData()
    }
    var u_superVC:UIViewController?
    var appear = KSImageSelectAppear()
    init(frame: CGRect,httpHeader:String,maxImgCount:Int = 8,numberOfRow:CGFloat = 4,picType:[PictureType] = [.takePicture,.albumPicture],scrollDirection:UICollectionView.ScrollDirection = .vertical,viewType:ImgViewType = .editable,appear:KSImageSelectAppear? = nil) {
        super.init(frame: frame)
        self.viewType = viewType
        self.maxImgCount = maxImgCount
        self.numberOfRow = numberOfRow
        self.picType = picType
        self.httpHeader = httpHeader
        self.scrollDirection = scrollDirection
        if appear.isSome {
            self.appear = appear!
        }
        
        self.initView()
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        self.initView()
    }
    func initView () {
        let coFrame = CGRect(x: self.bounds.minX, y: 0.8, width: self.bounds.width, height: self.bounds.height)
        self.collectionView = UICollectionView(frame: coFrame, collectionViewLayout: layout)
        self.addSubview(self.collectionView!)
      
      
        self.backgroundColor = self.appear.itembgColor
        self.collectionView?.backgroundColor = Theme.pureWhite()
        layout.itemSize = CGSize(width: self.ks_width/numberOfRow - numberOfRow * 2, height: self.ks_width/numberOfRow - numberOfRow * 2)
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 1
        layout.scrollDirection = self.scrollDirection
 
        
        self.collectionView?.collectionViewLayout = layout
        self.collectionView?.delegate = self
        self.collectionView?.dataSource = self
        self.collectionView?.contentInset = UIEdgeInsets(top: 5, left: 6, bottom: 5, right: 6)
        self.collectionView?.register(KSImageUtilCell.self, forCellWithReuseIdentifier: KSImageUtilCell.identifier)
        self.collectionView?.register(KSImgSeUtilHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: KSImgSeUtilHeader.identifier)
 
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let sumCount = self.dataArray.count
        
        if sumCount == maxImgCount { // 达到最大张数，那么就没有添加按钮了
            return sumCount
        } else {
            if viewType == .editable || viewType == .addable {
                return sumCount + 1
            } else {
                //只允许查看  或者  只允许删除的，就没有添加按钮了
                return sumCount
            }
            
        }
        
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell  = collectionView.dequeueReusableCell(withReuseIdentifier: KSImageUtilCell.identifier, for: indexPath as IndexPath) as! KSImageUtilCell
        let sumCount = self.dataArray.count
        if (indexPath.row == sumCount) {
            // 最后一项， 添加项，有这一项，说明
            if viewType == .viewOnly || viewType == .deletable {
                cell.imgBtn.isHidden = true
                cell.deleteBtn.isHidden = true
            } else {
                cell.imgBtn.isHidden = false
                cell.imgBtn.setBackgroundImage(UIImage(named:"ksphoto_add"), for: .normal)
                cell.imgBtn.setTitle("", for: .normal)
                cell.deleteBtn.isHidden = true
            }
            
            
        } else {
            var onex = dataArray[indexPath.row]
            if onex.type == .image {
                if onex.image.isSome {
                    cell.imgBtn.setBackgroundImage(onex.image, for: .normal)
                } else if let imgURL = URL(string: onex.url.unwrap) {
                    let source = KF.ImageResource(downloadURL: imgURL)
                    cell.imgBtn.kf.setBackgroundImage(with: source, for: .normal, placeholder: UIImage(named: "ld"), completionHandler: { result in
                        DispatchQueue.main.async {
                            switch result {
                                case .success(let img):
                                    onex.image = img.image
                                    cell.imgBtn.setBackgroundImage(img.image, for: .normal)
                                    cell.loadView.extHidden(hidden: true)
                                    break
                                case .failure(_):
                                    cell.imgBtn.setBackgroundImage(UIImage(named:"ks_error.jpg"), for: .normal)
                            }
                        }
                    })
                }
                cell.imgBtn.setTitle("", for: .normal)
            } else if onex.type == .video {
                let tempImg = onex.image.isSome ? onex.image! : UIImage(named:"video_default")
                cell.imgBtn.setBackgroundImage(tempImg, for: .normal)
                cell.imgBtn.setTitle("", for: .normal)
            } else { // 文件显示名字
                cell.imgBtn.setBackgroundImage(nil, for: .normal)
                cell.imgBtn.setTitle(onex.name.unwrap, for: .normal)
            }
            
            cell.imgBtn.isHidden = false
            
            cell.loadView.extHidden(hidden: (onex.isComplete ?? true || onex.image.isSome))
            
            if viewType == .viewOnly || viewType == .addable {
                cell.deleteBtn.isHidden = true
            } else {
                cell.deleteBtn.isHidden = false
            }
            
            
            
        }
        
        
        cell.imgBtn.tag = indexPath.row
        cell.imgBtn.addTarget(self, action:#selector(imgAction(sender:)) , for:.touchUpInside )
        cell.deleteBtn.tag = indexPath.row
        cell.deleteBtn.addTarget(self, action: #selector(deleteImg(sender:)), for: .touchUpInside)
        
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: KSImgSeUtilHeader.identifier, for: indexPath) as! KSImgSeUtilHeader
        
        
        header.titleLabel.text = appear.sectionTitle
        
         return header
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        var hh:CGFloat = 0
        if appear.sectionTitle.unwrap != "" {
            hh = imgUtilSectionH
        }
        return CGSize(width: KSGlobal.screenW, height: hh)
    }
 
    
    
    @objc func imgAction (sender:UIButton) {
        
        let sumCount = self.dataArray.count
        
        if (sender.tag == sumCount) {
            if dataArray.count == maxImgCount {
                KSToast("只能选\(maxImgCount)张")
                return
            }
            
            let alertSheet =  KSImagePicker.shared.config(picType: picType,cameraAction: { img in
                
                
                let imgsTreated = self.pretreatmentBeforeAddImgs([img])
                var temp = [VideoImg]()
                
                for i in 0..<imgsTreated.count {
                    let one = VideoImg( type: .image,image: imgsTreated[i],imageTp: .camera)
                    temp.append(one)
                }
                
                self.dataArray += temp
                
                if let delegate = self.ksDelegate {
                    delegate.addImages(self,imgs: imgsTreated)
                }
                if let delegate = self.ksDelegate {
                    delegate.addImages(self, imgvideos: temp)
                }
                self.collectionView?.reloadData()
                
            },photpMaxImagesCount:self.maxImgCount - self.dataArray.count,photoAction: { imgs,assets in
                
                var newPho = [UIImage]()
                let imgsTreated = self.pretreatmentBeforeAddImgs(imgs)
                newPho += imgsTreated
                
                var temp = [VideoImg]()
                
                for i in 0..<imgsTreated.count {
                    let assetOne = assets[i]
                    let ttt:SourType =  assetOne.mediaType == .video ? .video : .image
                    let one = VideoImg( type: ttt,image: imgsTreated[i],asset: assetOne,imageTp: .photoLibrary)
                    temp.append(one)
                }
                
                
                self.dataArray += temp
                
                if let delegate = self.ksDelegate {
                    delegate.addImages(self,imgs: newPho)
                }
                if let delegate = self.ksDelegate {
                    delegate.addImages(self, imgvideos: temp)
                }
                self.collectionView?.reloadData()
                
            },videoAction: {asset,mediaUrl,img in
                let temp = VideoImg(type: .video,image: img,asset: asset,mediaURL: mediaUrl)
                self.dataArray.append(temp )
                
                if let delegate = self.ksDelegate {
                    delegate.addImages(self, imgvideos: [temp])
                }
                self.collectionView?.reloadData()
                
            }) {
                
        
                let fileVC = UIDocumentPickerViewController(documentTypes: ["public.image", "public.audio", "public.movie", "public.text", "public.item", "public.content", "public.source-code"], in: .import)
                fileVC.delegate = self
                fileVC.modalPresentationStyle = .formSheet
                if let topVC = getTopVC() {
                    topVC.present_FullScreen(to: fileVC)
                }
                
            }
            
            if let delegate = self.ksDelegate {
                delegate.beginShowPicker()
            }
            // 3 跳转
            if let topVC = getTopVC() {
                topVC.present(alertSheet, animated: true, completion: nil)
            }
        }else {
            // MARK: - 预览
            
            if self.dataArray[sender.tag].type == .video {
                
                if self.dataArray[sender.tag].url.unwrap != "" {
                    let one = self.dataArray[sender.tag]
                    let urlX = one.url.unwrap
                    let cwebV = CommonWebController()
                    var urlXXX = ""
                    if urlX.contains("http") {
                        urlXXX = urlX
                    } else {
                        urlXXX = "\(self.httpHeader)\(urlX)"
                    }
                    cwebV.reportUrl = urlXXX
                    if let clipName = one.clipName {
                        cwebV.cacheFileName = "\(clipName).mp4"
                    }
                    cwebV.title = self.dataArray[sender.tag].name.unwrap
                    if let topVC = getTopVC() {
                        topVC.navigationController?.pushViewController(cwebV, animated: true)
                    }
                    
                } else if self.dataArray[sender.tag].asset.isSome {
                    let options = PHVideoRequestOptions()
                    options.isNetworkAccessAllowed = true
                    options.deliveryMode = .automatic
                    PHImageManager.default().requestPlayerItem(forVideo:self.dataArray[sender.tag].asset!, options: options, resultHandler: { playerItem, info in
                        //播放视频
                        let player = AVPlayer(playerItem: playerItem)
                        let playerVC = AVPlayerViewController()
                        playerVC.player = player
                        self.u_superVC!.present(playerVC, animated: true, completion: {
                            playerVC.player?.play()
                        })
                    })
                } else {
                    // 播放 mediaURL
                    
                    // 创建一个 AVPlayer 实例来播放视频
                    let player = AVPlayer(url: self.dataArray[sender.tag].mediaURL!)
                    
                    //                    // 如果你想在自定义的视图中播放视频，可以使用 AVPlayerLayer
                    //                    let playerLayer = AVPlayerLayer(player: player)
                    //                    playerLayer.frame = self.u_superVC!.bounds // 设置视频层的大小和位置
                    //                    self.u_superVC!.view.layer.addSublayer(playerLayer)
                    //                    player.play() // 开始播放视频
                    
                    // 或者，如果你想使用系统提供的播放界面，可以使用 AVPlayerViewController
                    let playerViewController = AVPlayerViewController()
                    playerViewController.player = player
                    self.u_superVC!.present(playerViewController, animated: true) {
                        playerViewController.player?.play()
                    }
                }
                
                
                
                
                
                
                
            } else if self.dataArray[sender.tag].type == .image {
                var photos = [SKPhoto]()
                // add some UIImage
                let temp = self.dataArray.filter { $0.type == .image }
                temp.forEach {
                    let sImg = $0.image.isSome ? $0.image! : UIImage(named:"ks_error.jpg")!
                    var image = SKPhoto.photoWithImage(sImg)
                    if $0.url != nil {
                        if KingfisherManager.shared.cache.diskStorage.isCached(forKey: $0.url!) {
                            do {
                                if let data = try KingfisherManager.shared.cache.diskStorage.value(forKey: $0.url!) {
                                    if let img = UIImage(data: data) {
                                        image = SKPhoto.photoWithImage(img)
                                    }
                                }
                            } catch {}
                        }
                    }
                    photos.append(image)
                }
                // 2. create PhotoBrowser Instance, and present from your viewController.
                let browser = SKPhotoBrowser(photos: photos)
                
                var browserIndex = sender.tag
                if let currUrl = self.dataArray[sender.tag].url {
                    if let imgIndex = temp.getIndexFor({$0.url == currUrl}) {
                        browserIndex = imgIndex
                    }
                }
                browser.initializePageIndex(browserIndex)
                if let topVC = getTopVC() {
                    topVC.present(browser, animated: true, completion: nil)
                }
                
                
            } else {  // .file
                
                let item = self.dataArray[sender.tag]
                
                if let urlX = item.url {
                    KSLog(urlX)
                    

                    let cwebV = CommonWebController()
                    var urlXXX = ""
                    if urlX.contains("http") {
                        urlXXX = urlX
                    } else {
                        urlXXX = "\(self.httpHeader)\(urlX)"
                    }
                    if ((item.name?.contains(".pdf")) != nil) {
                        cwebV.cacheFileName = item.name
                    }
                    cwebV.reportUrl = urlXXX
                    cwebV.title = self.dataArray[sender.tag].name.unwrap
                    if let topVC = getTopVC() {
                        topVC.navigationController?.pushViewController(cwebV, animated: true)
                    }
                
                    
                    
                } else {
                    
                    
                    if UIApplication.shared.canOpenURL(URL(string: "shareddocuments://")!) {
                        UIApplication.shared.open(URL(string: "shareddocuments://")!, options: [:], completionHandler: nil)
                    } else {
                        KSToast("请到文件app查看")
                    }
                }
                
            }
            
        }
    }
    // 删除项目，包括图片和文件
    @objc private  func deleteImg(sender:UIButton) {
        if let delegate = ksDelegate {
            delegate.deleteImage(self,index: sender.tag)
        }
    }
    // 删除本地项目，包括图片和文件
    func deleteLocalImg(tag:Int) {
        if self.dataArray.count > tag {
            self.dataArray.remove(at: tag)
            self.collectionView?.reloadData()
        }
        
    }
    // 全部删除，一般 用于重置
    func deleteAll() {
        self.dataArray.removeAll()
        self.collectionView?.reloadData()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func pretreatmentBeforeAddImgs(_ photos: [UIImage]) -> [UIImage] {
        if let delegate = ksDelegate {
            return  delegate.dealBeforeAddImages(self, imgs: photos)
        } else {
            return photos
        }
        
        
    }
    
    
}
enum DefaultImg {
    case loading,headIcon  // 默认图片  加载中 或  人物头像
}
extension KSImageSelectUtil {
    // 最新的展示方法，支持所有文件类型，以后都用这个方法替换
    public func newestShow(arr:[VideoImg]) {
        self.dataArray = arr
        self.collectionView?.reloadData()
    }
    //  展示所有图片
    public func showAllPicture(picS:[UIImage]) {
        self.dataArray = picS.compactMap { VideoImg(type: .image,image: $0)}
        self.collectionView?.reloadData()
    }
    
    // 用添加的形式展示图片
    public func addshowAllPicture(picS:[UIImage]) {
        self.dataArray += picS.compactMap { VideoImg(type: .image,image: $0)}
        self.collectionView?.reloadData()
    }
    // 展示所有文件
    public func showAllFiles(files:[VideoImg]) {
        self.dataArray = files
        self.collectionView?.reloadData()
    }
    // 用添加的形式展示文件
    public func addShowFiles(files:[VideoImg]) {
        self.dataArray += files
        self.collectionView?.reloadData()
    }
    /// 用url展示图片 支持 String  和 FileType
    public func showPicture(urls:[String],defaultImg:DefaultImg = .loading,backImgs:@escaping (([UIImage]?)->())) {
        
        
        guard urls.count > 0 else {
            self.dataArray.removeAll()
            self.collectionView?.reloadData()
            backImgs(nil)
            return
        }
        
        if defaultImg == .loading {
            let img = VideoImg(type: .image,image: UIImage.gif(name: "ks_jiazaizhong")!)
            self.dataArray = Array(repeating: img, count: urls.count)
        } else {
            let img = VideoImg(type: .image,image: UIImage.gif(name: "ks_avatarImage")!)
            self.dataArray = Array(repeating: img, count: urls.count)
        }
        
        
        let tempVO = self.viewType
        self.viewType = .viewOnly
        self.collectionView?.reloadData()
        DispatchQueue.global().async {
            for i in 0..<urls.count {
                getImageCacheOrnet(url: urls[i]) { vimg in
                    self.dataArray[i] = vimg
                    self.collectionView?.reloadData()
                }
                
            }
            DispatchQueue.main.async {
                // 主线程中
                self.viewType = tempVO
                self.collectionView?.reloadData()
                let imgArr = self.dataArray.compactMap { $0.image as? UIImage }
                backImgs(imgArr)
            }
            
        }
        
    }
    
    
    
    
}

extension KSImageSelectUtil:UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        if let first = urls.first  {
            first.startAccessingSecurityScopedResource()
            let fileCoordinator = NSFileCoordinator()
            let error = NSError()
            
            fileCoordinator.coordinate(readingItemAt: first, options: [], error: nil) { (newUrl) in
                
                let fileName = newUrl.lastPathComponent
                
                do {
                    if self.picType.contains(.pdfFile) && !self.picType.contains(.allfile) {
                        guard fileName.contains(".pdf") || fileName.contains(".PDF") else {
                            KSToast("该功能仅支持pdf格式")
                            return
                        }
                    }
                    
                    let fileData = try NSData(contentsOf: newUrl, options: .dataReadingMapped)
                    let model = VideoImg(type: .file,idkey: "",name: fileName, data: fileData as Data)
                    
                    self.dataArray.append(model)
                    self.collectionView?.reloadData()
                    if let delegate = ksDelegate {
                        delegate.addFiles(self, files: [model])
                    }
                    
                    first.stopAccessingSecurityScopedResource()
                    
                } catch {
                    print("error")
                    
                }
                
            }
            
        }
        
        
        print(urls)
    }
    
    
}
import Moya
import SVProgressHUD
func videoURLToData(videoURL: URL) -> Data? {
    do {
        // 尝试读取视频文件的内容到 Data 对象中
        let videoData = try Data(contentsOf: videoURL)
        return videoData
    } catch {
        // 处理读取文件时可能发生的错误
        print("Error reading video file: \(error.localizedDescription)")
        return nil
    }
}
// 给视频 PHAsset 格式异步转成 data ,用于上传
func dealVideoData(arr:[VideoImg],returnArr: @escaping  (([VideoImg])->()))  {
    var dataArray = arr
    
    let vArr = dataArray.filter{ $0.type == .video }
    if vArr.count > 0 {
        SVProgressHUD.show()
        // 创建调度组
        let workingGroup = DispatchGroup()
        for i in 0..<dataArray.count {
            if arr[i].type == .video {
                if dataArray[i].asset.isSome {
                    // 入组
                    workingGroup.enter()
                    assetToData(asset: dataArray[i].asset!, result: { data in
                        dataArray[i].data = data
                        // 出组
                        workingGroup.leave()
                    })
                }
                if dataArray[i].mediaURL.isSome {
                    // 入组
                    workingGroup.enter()
                    let data = videoURLToData(videoURL: dataArray[i].mediaURL!)
                    dataArray[i].data = data
                    // 出组
                    workingGroup.leave()
                }
                
            }
        }
        // 调度组里的任务都执行完毕
        workingGroup.notify(queue: .main) {
            SVProgressHUD.dismiss()
            returnArr(dataArray)
        }
    } else {
        returnArr(dataArray)
    }
    
    
}
//  paramName 服务端接收的参数名
func videoImgArr2MultiData(arr:[VideoImg],paramName:String) -> [MultipartFormData] {
    var formDataAry = [MultipartFormData]()
    
    for (i,one) in arr.enumerated() {
        let fname = getAttachName(i: i)
        if one.type == .image {
            var name = ""
            if one.clipName.unwrap != "" {
                name = one.clipName.unwrap.lowercased()
                
            } else if one.name.unwrap != "" {
                name = one.name.unwrap.lowercased()
                
            } else {
                name = "\(fname).jpg"
            }
            var dadd:Data!
            if one.data.isSome {
                dadd = one.data!
            } else {
                dadd = resetImgSize(sourceImage: one.image!, maxImageLenght: filemaxImageLenght, maxSizeKB: filemaxSizeKB)
            }
          
            let formData = MultipartFormData(provider: .data(dadd), name: paramName, fileName: name, mimeType: "image/jpg")
            
            formDataAry.append(formData)
            
        } else if one.type == .file {
            var name = ""
            if one.clipName.unwrap != "" {
                name = one.clipName.unwrap.lowercased()
                
            } else if one.name.unwrap != "" {
                name = one.name.unwrap.lowercased()
            } else {
                name = "\(fname).pdf"
            }
            let formData = MultipartFormData(provider: .data(one.data!), name: paramName, fileName: name, mimeType: "image/pdf")
            formDataAry.append(formData)
        } else {
            var name = ""
            if one.clipName.unwrap != "" {
                name = one.clipName.unwrap.lowercased()
                
            } else if one.name.unwrap != "" {
                name = one.name.unwrap.lowercased()
            } else {
                name = "\(fname).mp4"
            }
            let formData = MultipartFormData(provider: .data(one.data!), name: paramName, fileName: name, mimeType: "image/mp4")
            formDataAry.append(formData)
        }
        
    }
    
        return formDataAry
   
    
}
 
@MainActor func getImageCacheOrnet(url:String, clipName: String = "", ignoreNet: Bool = false, imgBackClo: @escaping (VideoImg) -> ()) {
    
    
    // 增加根据文件名获取
    if clipName.count > 0 {
        if let diskImg = FileCacheTool.getImage(fileName: "\(clipName).jpg") {
            imgBackClo(VideoImg(type: .image, image: diskImg))
            return
        }
    }
    
    // ImageCache，默认是
    let cache = ImageCache.default
    // 判定图片是否存在
    let cached = cache.imageCachedType(forKey:url)
    var cachedImg:UIImage?
    if  cached == .disk {
        cache.retrieveImageInDiskCache(forKey: url, completionHandler: { (result) in
            switch result {
            case .success(let img):
                KSLog("硬盘获取：\(url)")
                imgBackClo(VideoImg(type: .image,image: img!))
            default:
                break
            }
        })
        
    } else if cached == .memory {
        cachedImg = cache.retrieveImageInMemoryCache(forKey:url)
        KSLog("内存获取：\(url)")
        imgBackClo(VideoImg(type: .image,image: cachedImg!))
    } else if ignoreNet {
        imgBackClo(VideoImg(type: .image, image: nil))
    } else {
        if let loadURL = URL(string: url) {
            let source = KF.ImageResource(downloadURL: loadURL)
            UIImageView().kf.setImage(with: source) { result in
                switch result {
                case .success(let img):
                    imgBackClo(VideoImg(type: .image, image: img.image))
                    break
                case .failure(_):
                    imgBackClo(VideoImg(type: .image, image: nil))
                }
            }
        } else {
            imgBackClo(VideoImg(type: .image, image: nil))
        }
    }
}
class KSImgSeUtilHeader: UICollectionReusableView {
    
    var titleLabel: UILabel!
   
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = Theme.pureWhite()
        titleLabel = UILabel()
        titleLabel.textColor = titleColorLightGray
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self) 
            make.centerY.equalTo(self)
        }
         
        
    }
 
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
// 统一命名附件
func getAttachName(i:Int) -> String {
    return "\(USERINFO.usrid ?? "")\(Date.nowTimeToString)_\(i + 1)"
}
 
